﻿using MySqlConnector;

namespace Infrastructure.Persistence;

public class MySqlDataProvider : BoilerplateDataProvider
{
    public override bool CreateDatabaseIfNotExists(string connectionString)
    {
        (connectionString, var databaseName) = GetConnectionStringFormat(connectionString);

        // 检查数据库是否已经存在
        if (DatabaseExists(databaseName, connectionString))
        {
            Console.WriteLine($"Database '{databaseName}' already exists.");
            return false;
        }
        using MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
        mySqlConnection.Open();

        using MySqlCommand command = mySqlConnection.CreateCommand();
        command.CommandText = $"CREATE DATABASE IF NOT EXISTS `{databaseName}`";
        command.ExecuteNonQuery();

        Console.WriteLine($"Database '{databaseName}' created successfully.");

        return true;
    }
    public override bool DatabaseExists(string databaseName, string connectionString)
    {

        using MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
        mySqlConnection.Open();

        using MySqlCommand command = mySqlConnection.CreateCommand();
        command.CommandText = $"SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name='{databaseName}'";

        long? count = (long?)command.ExecuteScalar();
        return count.HasValue && count.Value > 0;
    }
}
